﻿var WS = {
		sources: {},
		websocket:null,
		status:0,//0代表未初始化，1，代表open，2，代表正在open，3代表错误，或关闭。
		url:"ws://yun.sankai.com/cloud-websocket/zhy_websocket",
		sockjsurl:"https://yun.sankai.com/cloud-websocket/sockjs/zhy_websocket/info",
		onopen:function(){},
		onclose:function(){},
		onerror:function(){},
		ondata:function(json){
			if(json=="1"){
				return;
			}
			var data=eval('(' + json + ')');
			var callbacks=WS.sources[data.source];
			if(typeof callbacks =="function"){
				if(data.type=="data"){
					callbacks(data.data);
				}
			}
			if(typeof callbacks =="object"){
				if(data.type=="data"){
					if(callbacks.ondata){
						callbacks.ondata(data.data);
					}
				}
				if(data.type=="listenCallback"){
					if(callbacks.listenCallback){
						callbacks.listenCallback(data.data);
					}
				}
				if(data.type=="leaveCallback"){
					if(callbacks.leaveCallback){
						callbacks.leaveCallback(data.data);
					}
				}
				
			}
		},

		leave: function(source) {
			if(WS.status!=1)return;
			delete WS.sources[source];
			websocket.send("{'action':'leave','source':'"+source+"'}");
		},

		listen: function(source,callbacks) {
			WS.sources[source]=callbacks;
			if(WS.websocket==null&&WS.status==0){
				WS.init();
				return;
			}
			if(WS.status==3)return;
			
			if(WS.status==2){
				setTimeout(function(){
					WS.listen(source,callbacks);
				},500);
				return;
			}
			if(WS.status==1){
				websocket.send("{'action':'listen','source':'"+source+"'}");
			}
			
		},

		init: function () {
			WS.status=2;
			WS.heartbeat();
	        if ('WebSocket' in window) {
	           websocket = new WebSocket(WS.url);
	        }else {
	           websocket = new SockJS(WS.sockjsurl);
	        } 
			websocket.onopen = function(){
				WS.status=1;
				for (var i in WS.sources){
					websocket.send("{'action':'listen','source':'"+i+"'}");
				}
				WS.onopen();
			}; 
			websocket.onmessage = function(e){
				WS.ondata(e.data);
			}; 
			websocket.onclose = function(e){
				
				WS.status=3;
			}; 
			websocket.onerror = function(e){
				WS.status=3;
			};
		},
		heartbeat:function(){
			if(WS.status!=2){
				if(!websocket || websocket.readyState != 1){
					websocket=null;
					WS.init();
					return;
				}
				websocket.send("1");
			}
			setTimeout(function(){
				WS.heartbeat();
			},30000);
		}
		
	}

	function listen(source,callbacks) {
		
		WS.listen(source,callbacks);
	}